package com.wyl.home.search

import android.view.View
import androidx.databinding.ObservableArrayList
import com.library.flowlayout.FlowLayoutManager
import com.wuhenzhizao.titlebar.widget.CommonTitleBar
import com.wyl.base.SearchCache
import com.wyl.base.SearchKeyList
import com.wyl.home.R
import com.wyl.libbase.base.NormalActivity
import com.wyl.libbase.binding.recyclerview.RecyclerViewSpace
import com.wyl.libbase.utils.ACache
import com.wyl.libbase.extend.openActivity
import com.wyl.libbase.extend.toast
import io.ditclear.bindingadapter.ItemClickPresenter
import io.ditclear.bindingadapter.SingleTypeAdapter
import kotlinx.android.synthetic.main.search_activity.*

class SearchActivity : NormalActivity(), ItemClickPresenter<String> {
    private val cache by lazy { ACache.get(this, SearchCache) }
    private val dataSource = ObservableArrayList<String>()

    override fun getLayoutId(): Int = R.layout.search_activity

    override fun initView() {
        titlebar.apply {
            centerSearchEditText.hint = "请输入关键词搜索"
//            centerSearchRightImageView.visibility = View.GONE

            setListener { _, action, extra ->
                when (action) {
                    CommonTitleBar.ACTION_LEFT_BUTTON -> onBackPressed()
                    CommonTitleBar.ACTION_SEARCH_SUBMIT -> searchKey(extra)
                    CommonTitleBar.ACTION_RIGHT_TEXT -> searchKey(searchKey)
                    else -> {
                    }
                }
            }
        }

        recyclerView.apply {
            layoutManager = FlowLayoutManager()
            adapter = mAdapter
            addItemDecoration(RecyclerViewSpace(30, 0, 12))
        }

        delete.setOnClickListener {
            dataSource.clear()
            cache.clear()
        }
    }

    private val mAdapter by lazy {
        SingleTypeAdapter(
            this,
            R.layout.search_item,
            dataSource
        ).apply {
            itemPresenter = this@SearchActivity
        }
    }

    override fun onItemClick(v: View, item: String) {
        searchKey(item)
    }

    override fun loadData() {
        var cacheData: List<String>?
        try {
            cacheData = cache.getAsObject(SearchKeyList) as List<String>
        } catch (e: TypeCastException) {
            cacheData = null
        }
        cacheData?.apply { dataSource.addAll(this) }
    }

    private fun searchKey(key: String) {
        if (key.isEmpty()) {
            toast("请输出关键字")
            return
        }
        dataSource.add(key)
        openActivity(SearchListActivity::class.java) { putExtra("key", key) }
    }

    override fun onDestroy() {
        cache.put(SearchKeyList, dataSource)
        super.onDestroy()
    }

}
